<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\scanwork\Order;
use app\admin\model\scanwork\Allocation;
use app\admin\model\scanwork\Report;
use app\admin\model\scanwork\Product;
use app\admin\model\scanwork\ProductModel;
use app\admin\model\scanwork\Process;
use think\Db;
use think\Exception;

/**
 * 千牛小程序前端用户API控制器（员工端）
 */
class QianniuFrontend extends Api
{
    protected $noNeedLogin = ['login', 'autoLogin', 'checkToken', 'getUserInfo', 'profile', 'getTodayStats', 'getUnreadMessageCount', 'getLatestMessages', 'getTasks', 'getMyAllocations', 'submitReport', 'submitActiveReport', 'getMyReports'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        
        // 支持Bearer token格式
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7);
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
    }

    /**
     * 千牛小程序登录
     */
    public function login()
    {
        $code = $this->request->post('code');
        $corpId = $this->request->post('corp_id');
        
        if (!$code || !$corpId) {
            $this->error('参数不完整');
        }
        
        try {
            // 获取千牛用户信息
            $qianniuUserInfo = $this->getQianniuUserInfo($code, $corpId);
            if (!$qianniuUserInfo) {
                $this->error('千牛登录失败');
            }
            
            // 查找或创建用户
            $user = $this->findOrCreateQianniuUser($qianniuUserInfo);
            
            // 生成token
            $token = md5($user->id . time() . rand(1000, 9999));
            
            // 保存千牛用户信息到session
            $sessionData = [
                'user_id' => $user->id,
                'qianniu_user_id' => $qianniuUserInfo['userid'],
                'corp_id' => $corpId,
                'name' => $qianniuUserInfo['name'],
                'department_ids' => $qianniuUserInfo['department_ids'] ?? [],
                'position' => $qianniuUserInfo['position'] ?? ''
            ];
            session('qianniu_user_info', $sessionData);
            session('qianniu_token', $token);
            
            // 同时保存到数据库
            $user->qianniu_token = $token;
            $user->qianniu_token_expire = time() + 7200; // 2小时过期
            $user->save();
            
            $this->success('登录成功', [
                'token' => $token,
                'user_info' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'qianniu_user_id' => $qianniuUserInfo['userid'],
                    'name' => $qianniuUserInfo['name'],
                    'is_admin' => false
                ]
            ]);
            
        } catch (Exception $e) {
            $this->error('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 自动登录
     */
    public function autoLogin()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $user = User::where('qianniu_token', $token)
                   ->where('qianniu_token_expire', '>', time())
                   ->find();
        
        if (!$user) {
            $this->error('token无效或已过期');
        }

        $this->success('自动登录成功', [
            'user_info' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname,
                'is_admin' => false
            ]
        ]);
    }

    /**
     * 验证token
     */
    public function checkToken()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $user = User::where('qianniu_token', $token)
                   ->where('qianniu_token_expire', '>', time())
                   ->find();
        
        if (!$user) {
            $this->error('token无效或已过期');
        }

        $this->success('token有效', [
            'user_info' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'qianniu_user_id' => $user->qianniu_user_id,
                'name' => $user->nickname,
                'is_admin' => false
            ]
        ]);
    }

    /**
     * 获取千牛用户信息
     */
    private function getQianniuUserInfo($code, $corpId)
    {
        $qianniuConfig = config('qianniu');
        $appId = $qianniuConfig['app_id'];
        $clientId = $qianniuConfig['app_key'];
        $clientSecret = $qianniuConfig['app_secret'];
        
        try {
            $url = "https://open.dingtalk.com/api/auth/userinfo";
            $data = [
                'access_token' => $this->getAccessToken($clientId, $clientSecret),
                'code' => $code
            ];
            
            $response = $this->httpPost($url, $data);
            $result = json_decode($response, true);
            
            // 添加调试日志
            error_log("千牛API响应: " . json_encode($result));
            
            if (isset($result['userid'])) {
                return [
                    'userid' => $result['userid'],
                    'name' => $result['name'] ?? '千牛用户',
                    'department_ids' => $result['department_ids'] ?? [1],
                    'position' => $result['position'] ?? '员工'
                ];
            } else {
                error_log("千牛API返回错误: " . json_encode($result));
            }
        } catch (Exception $e) {
            error_log("千牛API调用异常: " . $e->getMessage());
        }
        
        // 返回模拟数据
        return [
            'userid' => 'qianniu_' . substr(md5($code), 0, 8),
            'name' => '千牛用户',
            'department_ids' => [1, 2],
            'position' => '员工'
        ];
    }
    
    /**
     * 获取千牛访问令牌
     */
    private function getAccessToken($clientId, $clientSecret)
    {
        $url = "https://open.dingtalk.com/api/auth/getAccessToken";
        $data = [
            'appkey' => $clientId,
            'appsecret' => $clientSecret
        ];
        
        $response = $this->httpPost($url, $data);
        $result = json_decode($response, true);
        
        return $result['access_token'] ?? '';
    }
    
    /**
     * HTTP POST请求
     */
    private function httpPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Accept: application/json'
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return $response;
    }

    /**
     * 查找或创建千牛用户
     */
    private function findOrCreateQianniuUser($qianniuUserInfo)
    {
        $user = User::where('qianniu_user_id', $qianniuUserInfo['userid'])->find();
        
        if (!$user) {
            $userData = [
                'username' => 'qn_' . $qianniuUserInfo['userid'],
                'nickname' => $qianniuUserInfo['name'],
                'qianniu_user_id' => $qianniuUserInfo['userid'],
                'openid' => 'qianniu_' . $qianniuUserInfo['userid'],
                'wechat_openid' => 'qianniu_wechat_' . $qianniuUserInfo['userid'] . '_' . time() . '_' . rand(1000, 9999),
                'status' => 'normal',
                'createtime' => time()
            ];
            $user = User::create($userData);
        }
        
        return $user;
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $user = $this->getCurrentUser();
        
        $userInfo = [
            'id' => $user->id,
            'nickname' => $user->nickname,
            'qianniu_user_id' => $user->qianniu_user_id,
            'name' => $user->nickname,
            'is_admin' => false
        ];
        
        $this->success('获取成功', $userInfo);
    }

    /**
     * 获取用户个人资料统计
     */
    public function profile()
    {
        $user = $this->getCurrentUser();
        
        // 统计用户的任务数量
        $totalTasks = Allocation::where('user_id', $user->id)->count();
        
        // 统计用户的报工数量
        $totalReports = Report::where('user_id', $user->id)->count();
        
        // 统计用户的总工资
        $totalWage = Report::where('user_id', $user->id)
            ->where('status', 1) // 已审核
            ->sum('wage');
        
        $stats = [
            'totalTasks' => $totalTasks,
            'totalReports' => $totalReports,
            'totalWage' => $totalWage
        ];
        
        $this->success('获取成功', $stats);
    }

    /**
     * 获取今日统计
     */
    public function getTodayStats()
    {
        $user = $this->getCurrentUser();
        
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $taskCount = Allocation::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->count();
        
        // 今日报工数
        $reportCount = Report::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->count();
        
        // 今日工资
        $wage = Report::where('user_id', $user->id)
            ->where('createtime', '>=', $startTime)
            ->where('createtime', '<=', $endTime)
            ->where('status', 1) // 已审核
            ->sum('wage');
        
        $this->success('获取成功', [
            'todayTaskCount' => $taskCount,
            'todayReportCount' => $reportCount,
            'todayWage' => $wage
        ]);
    }

    /**
     * 获取未读消息数量
     */
    public function getUnreadMessageCount()
    {
        $user = $this->getCurrentUser();
        
        // 这里可以根据实际的消息表来统计未读消息数量
        // 暂时返回0，表示没有未读消息
        $unreadCount = 0;
        
        $this->success('获取成功', ['count' => $unreadCount]);
    }

    /**
     * 获取最新消息
     */
    public function getLatestMessages()
    {
        $user = $this->getCurrentUser();
        $limit = $this->request->get('limit', 10);
        
        // 这里可以根据实际需求实现消息系统
        // 暂时返回模拟数据
        $messages = [
            [
                'id' => 1,
                'title' => '系统通知',
                'content' => '欢迎使用工厂报工系统',
                'type' => 'system',
                'createtime' => time()
            ]
        ];
        
        $this->success('获取成功', $messages);
    }

    /**
     * 获取任务列表
     */
    public function getTasks()
    {
        $user = $this->getCurrentUser();
        
        $allocations = Allocation::with(['order', 'model', 'process'])
            ->where('user_id', $user->id)
            ->where('status', 0) // 未完成
            ->order('createtime desc')
            ->select();
        
        $tasks = [];
        foreach ($allocations as $allocation) {
            $tasks[] = [
                'id' => $allocation->id,
                'order_no' => $allocation->order ? $allocation->order->order_no : '',
                'model_name' => $allocation->model ? $allocation->model->name : '',
                'process_name' => $allocation->process ? $allocation->process->name : '',
                'quantity' => $allocation->quantity,
                'createtime' => $allocation->createtime
            ];
        }
        
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取我的分工任务
     */
    public function getMyAllocations()
    {
        $user = $this->getCurrentUser();
        
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = ['user_id' => $user->id];
        if ($status !== '') {
            $where['status'] = $status;
        }
        
        $list = Allocation::with(['order', 'model.product', 'process'])
            ->where($where)
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
            
        $this->success('获取成功', [
            'total' => $list->total(),
            'list' => $list->items()
        ]);
    }

    /**
     * 提交报工
     */
    public function submitReport()
    {
        $user = $this->getCurrentUser();
        
        $allocationId = $this->request->post('allocation_id');
        $itemNos = $this->request->post('item_nos/a', []);
        $workType = $this->request->post('work_type', 'piece');
        $workHours = floatval($this->request->post('work_hours', 0));
        $remark = $this->request->post('remark', '');
        
        if (empty($allocationId)) {
            $this->error('分工ID不能为空');
        }
        
        $allocation = Allocation::where(['id' => $allocationId, 'user_id' => $user->id])->find();
        if (!$allocation) {
            $this->error('分工任务不存在');
        }
        
        $exists = Report::where('allocation_id', $allocationId)->find();
        if ($exists) {
            $this->error('该任务已报工');
        }
        
        Db::startTrans();
        try {
            $wage = 0;
            if ($allocation->work_type == 'piece') {
                $wage = count($itemNos) * $allocation->piece_price;
            } else {
                $wage = $workHours * $allocation->time_price;
            }
            
            $reportData = [
                'allocation_id' => $allocationId,
                'user_id' => $user->id,
                'quantity' => count($itemNos),
                'work_hours' => $workHours,
                'wage' => $wage,
                'remark' => $remark,
                'item_nos' => json_encode($itemNos),
                'status' => 0,
                'createtime' => time()
            ];
            
            $report = Report::create($reportData);
            
            $allocation->status = 1;
            $allocation->save();
            
            Db::commit();
            $this->success('报工成功', $report);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('报工失败：' . $e->getMessage());
        }
    }

    /**
     * 提交主动报工
     */
    public function submitActiveReport()
    {
        $user = $this->getCurrentUser();
        
        $orderNo = $this->request->post('order_no');
        $productId = $this->request->post('product_id');
        $processId = $this->request->post('process_id');
        $quantity = intval($this->request->post('quantity'));
        $workHours = floatval($this->request->post('work_hours'));
        $remark = $this->request->post('remark', '');
        $images = $this->request->post('images/a', []);
        
        if (!$orderNo || !$productId || !$processId || !$quantity || !$workHours) {
            $this->error('必填字段不能为空');
        }
        
        // 检查产品是否存在
        $product = Product::get($productId);
        if (!$product) {
            $this->error('产品不存在');
        }
        
        // 检查工序是否存在
        $process = Process::get($processId);
        if (!$process) {
            $this->error('工序不存在');
        }
        
        Db::startTrans();
        try {
            // 计算工资
            $wage = 0;
            if ($process->work_type == 'piece') {
                $wage = $quantity * $process->piece_price;
            } else {
                $wage = $workHours * $process->time_price;
            }
            
            $reportData = [
                'user_id' => $user->id,
                'order_no' => $orderNo,
                'product_id' => $productId,
                'process_id' => $processId,
                'quantity' => $quantity,
                'work_hours' => $workHours,
                'wage' => $wage,
                'remark' => $remark,
                'images' => json_encode($images),
                'status' => 0, // 待审核
                'createtime' => time()
            ];
            
            $report = Report::create($reportData);
            
            Db::commit();
            $this->success('提交成功', $report);
            
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败：' . $e->getMessage());
        }
    }

    /**
     * 获取我的报工记录
     */
    public function getMyReports()
    {
        $user = $this->getCurrentUser();
        
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $status = $this->request->get('status', '');
        
        $where = ['user_id' => $user->id];
        if ($status !== '') {
            $where['status'] = $status;
        }
        
        $list = Report::with(['allocation.order', 'allocation.model.product', 'allocation.process'])
            ->where($where)
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $items = $list->items();
        foreach ($items as &$item) {
            $item['statusText'] = $this->getReportStatusText($item['status']);
        }
        
        $this->success('获取成功', [
            'total' => $list->total(),
            'list' => $items
        ]);
    }

    /**
     * 获取报工状态文本
     */
    private function getReportStatusText($status)
    {
        $statusMap = [
            0 => '待审核',
            1 => '已通过',
            2 => '已拒绝'
        ];
        return $statusMap[$status] ?? '未知';
    }

    /**
     * 获取当前用户
     */
    private function getCurrentUser()
    {
        $token = $this->request->header('Authorization');
        if (!$token) {
            $this->error('未提供token');
        }

        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        $user = User::where('qianniu_token', $token)
                   ->where('qianniu_token_expire', '>', time())
                   ->find();
        
        if (!$user) {
            $this->error('token无效或已过期');
        }

        return $user;
    }
}
